﻿unit Kges;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls, jpeg,Engine,Screen1, ScktComp;

type
  TForm1 = class(TForm)
    Splitter1: TSplitter;
    Timer1: TTimer;
    fTop: TImage;
    Image2: TImage;
    lblTime: TLabel;
    lblDate: TLabel;
    lblWeek: TLabel;
    tmrQuery: TTimer;
    ClientSocket1: TClientSocket;
    Reconnect: TTimer;
    procedure GradientRect (FromRGB, ToRGB: TColor; Canvas: TCanvas);
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure DayDataChange(Sender: TObject);
	procedure YesterDayDataChange(Sender: TObject);
    procedure MonthDataChange(Sender: TObject);
    procedure YearDataChange(Sender: TObject);
    procedure tmrQueryTimer(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormActivate(Sender: TObject);
    procedure Get_SA_Date();
    procedure ReconnectTimer(Sender: TObject);
    procedure ClientSocket1Connect(Sender: TObject; Socket: TCustomWinSocket);
    procedure ClientSocket1Disconnect(Sender: TObject;
      Socket: TCustomWinSocket);
    procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
      ErrorEvent: TErrorEvent; var ErrorCode: Integer);
    procedure ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
  private
    { Private declarations }
  public
    d : TData;		//!!! ОБЪЕКТ КЛАССА описанного в Engine
    { Public declarations }
  end;
  Tt = record
    CT34, CT124, CT103, CT697, CT572, CT2221 : Real;  //Темпиратуры для  КГЭС
  end;
var
  Form1: TForm1;
  Screens : array [0..2] of TScreens;

const
  IpAddrSemp = '192.168.213.2';

implementation

uses dm,DateUtils,Math;
{$R *.dfm}

procedure TForm1.ClientSocket1Connect(Sender: TObject;
  Socket: TCustomWinSocket);
begin
  Reconnect.Enabled := False;
end;

procedure TForm1.ClientSocket1Disconnect(Sender: TObject;
  Socket: TCustomWinSocket);
begin
  Reconnect.Enabled := True;
end;

procedure TForm1.ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
  ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
  ErrorCode := 0;
end;

procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
var
  rmesg : Tt;
  txt : AnsiString;
  len : Integer;
begin
  Socket.ReceiveBuf(rmesg,Socket.ReceiveLength);
  (Screens[0] as TfrmScreen1).zCT34.Caption := FloatToStr(rmesg.CT34);
  (Screens[0] as TfrmScreen1).zCT124.Caption := FloatToStr(rmesg.CT124);
  (Screens[0] as TfrmScreen1).zCT572.Caption := FloatToStr(rmesg.CT572);
end;

procedure TForm1.DayDataChange(Sender: TObject);
begin
  if not ((Screens[0] as TfrmScreen1).lblConsumedDay.Caption = FloatToStr(RoundTo(d.ConsumedDay,-0))+ '    ') then
  (Screens[0] as TfrmScreen1).stbStatus.Panels[0].Text := 'Последнее обновление '+ lblTime.Caption;
  (Screens[0] as TfrmScreen1).lblConsumedDay.Caption := FloatToStr(RoundTo(d.ConsumedDay,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblGeneratedDay.Caption := FloatToStr(RoundTo(d.GeneratedDay,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblVidachaDay.Caption := FloatToStr(RoundTo(d.GeneratedDay - d.ConsumedDay,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblVPS110Day.Caption := FloatToStr(RoundTo(d.LossesDay,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblLossesDay.Caption := FloatToStr(RoundTo(d.GeneratedDay - d.ConsumedDay-d.LossesDay,-0))+ '    ';
end;

procedure TForm1.YesterDayDataChange(Sender: TObject);
begin  
  (Screens[0] as TfrmScreen1).lblConsumedYesterDay.Caption := FloatToStr(RoundTo(d.ConsumedYesterDay,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblGeneratedYesterDay.Caption := FloatToStr(RoundTo(d.GeneratedYesterDay,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblVidachaYesterDay.Caption := FloatToStr(RoundTo(d.GeneratedYesterDay - d.ConsumedYesterDay,-0))+ '    ';
//  (Screens[0] as TfrmScreen1).lblVPS110YesterDay.Caption := FloatToStr(RoundTo(d.LossesYesterDay,-2))+ '    ';
//  (Screens[0] as TfrmScreen1).lblLossesYesterDay.Caption := FloatToStr(RoundTo(d.GeneratedYesterDay - d.ConsumedYesterDay-d.LossesYesterDay,-2))+ '    ';
end;

procedure TForm1.MonthDataChange(Sender: TObject);
begin
  (Screens[0] as TfrmScreen1).lblConsumedMonth.Caption := FloatToStr(RoundTo(d.ConsumedMonth,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblGeneratedMonth.Caption := FloatToStr(RoundTo(d.GeneratedMonth,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblVidachaMonth.Caption := FloatToStr(RoundTo(d.GeneratedMonth - d.ConsumedMonth,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblVPS110Month.Caption := FloatToStr(RoundTo(d.LossesMonth,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblLossesMonth.Caption := FloatToStr(RoundTo(d.GeneratedMonth - d.LossesMonth- d.ConsumedMonth,-0))+ '    ';
end;

procedure TForm1.ReconnectTimer(Sender: TObject);
begin
  ClientSocket1.Close();
  ClientSocket1.Open();
end;

procedure TForm1.YearDataChange(Sender: TObject);
begin
  (Screens[0] as TfrmScreen1).lblConsumedYear.Caption := FloatToStr(RoundTo(d.ConsumedYear,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblGeneratedYear.Caption := FloatToStr(RoundTo(d.GeneratedYear,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblVidachaYear.Caption := FloatToStr(RoundTo(d.GeneratedYear - d.ConsumedYear,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblVPS110Year.Caption := FloatToStr(RoundTo(d.LossesYear,-0))+ '    ';
  (Screens[0] as TfrmScreen1).lblLossesYear.Caption := FloatToStr(RoundTo(d.GeneratedYear - d.LossesYear- d.ConsumedYear,-0))+ '    ';
end;




procedure TForm1.FormActivate(Sender: TObject);
begin
  Timer1Timer(Sender);
  Get_SA_Date();
  d.DayQuery();
  d.YesterDayQuery();
  d.MonthQuery();
  d.YearQuery();
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  d.oraq.Cancel;
  d.Terminate;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  inherited;
  Screens[0] := TfrmScreen1.Create(self);
  Screens[0].Parent := Form1;
  Screens[0].Align := alClient;
  Screens[0].Show;
  ClientSocket1.Address := IpAddrSemp;
  ClientSocket1.Port := 38002;
  ClientSocket1.Open();
  d := TData.Create(False);
  d.FreeOnTerminate := True;
  d.OnDayDataChange := DayDataChange;	//событию присваивается выполняемая функция
  d.OnYesterDayDataChange := YesterDayDataChange;
  d.OnMonthDataChange :=  MonthDataChange;	
  d.OnYearDataChange := YearDataChange;
  d.Init();
//    GradientRect (clHighlight, clTeal, fTop.Canvas) ;
//    GradientRect (clTeal, clTeal, fDown.Canvas) ;

end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  ClientSocket1.Socket.SendText(' ');
  if not fdm.OraSession1.Connected then fdm.OraSession1.Connect;
 // lblDate.Caption := DateToStr(Now);
  fdm.OraQuery1.Open;
  d.DateNow := EncodeDateTime(
  YearOf(fdm.OraQuery1.Fields[0].AsDateTime),
  MonthOf(fdm.OraQuery1.Fields[0].AsDateTime),
  DayOf(fdm.OraQuery1.Fields[0].AsDateTime),
  HourOf(fdm.OraQuery1.Fields[0].AsDateTime),
  MinuteOf(fdm.OraQuery1.Fields[0].AsDateTime),
  SecondOf(fdm.OraQuery1.Fields[0].AsDateTime),0);
  lblTime.Caption := FormatDateTime('HH:MM:SS', fdm.OraQuery1.Fields[0].AsDateTime);
  lblDate.Caption := FormatDateTime('yyyy-dd-mm', fdm.OraQuery1.Fields[0].AsDateTime) ;
  lblWeek.Caption := LongDayNames[DayOfWeek(fdm.OraQuery1.Fields[0].AsDateTime)];
  fdm.OraQuery1.Close;
  //lblTime.Caption := DateTimeToStr(d.DateNow);
end;


procedure TForm1.tmrQueryTimer(Sender: TObject);
begin
  Get_SA_Date();
  d.DayQuery();
  d.YesterDayQuery();
  d.MonthQuery();
  d.YearQuery();
end;

procedure TForm1.Get_SA_Date;
var
  data : String;
  val : Real;
  val_yesterday : Real;
  val_sutochn : Real;
  val_month : Real;
  val_year : Real;
  i : integer;

  sum_sa_teplo_yesterday : Real;
  sum_sa_teplo:Real;
  sum_sa_teplo_month:Real;
  sum_sa_teplo_year:Real;
  tepl_sa_obsh_yesterday : Real;
  tepl_sa_obsh : Real;
  tepl_sa_obsh_month : Real;
  tepl_sa_obsh_year : Real;

  myYear, myMonth, myDay : Word;
  date_month_before: TDateTime;
  date_now:TDateTime;
begin
  with fdm.ADOQuery1 do
  begin

  sum_sa_teplo_yesterday:=0;
  sum_sa_teplo:=0;
  sum_sa_teplo_month:=0;
  sum_sa_teplo_year:=0;
  tepl_sa_obsh_month:=0;
  tepl_sa_obsh_year:=0;
    //1 Теплосчетчик
    for I := 0 to 12 do
    begin
      (Screens[0] as TfrmScreen1).StringGrid1.Cells[i+1,0] := 'M'+IntToStr(i+1);  // именование столбцов

      //последнее значение по теплосчетчикам(показывает всю выработку-счетчик)
      SQL.Clear;
      SQL.Add('SELECT TOP 1  * From FloatTable where TagIndex='+IntToStr(i)+' order by dateandtime desc');
      Open;
      data := FieldByName('DateAndTime').AsString;

      date_now:=  FieldByName('DateAndTime').AsDateTime;  // текущее время с сервера
      DecodeDate(date_now, myYear, myMonth, myDay);     //дата с сервера в формате WORD



      val := FieldByName('Val').AsFloat;              // текущее показание
      (Screens[0] as TfrmScreen1).StringGrid1.Cells[i+1,1] := FloatToStr(RoundTo(val,-2));  //заполнение
      Close;


                            //  по каждому теплосчетчику с начала суток
      SQL.Clear;
      SQL.Add('SELECT  * From FloatTable where dateandtime > '''+lblDate.Caption+' 00:00:00''  and TagIndex='+IntToStr(i)+' order by dateandtime'); //значение
      Open;
      data := FieldByName('DateAndTime').AsString;
      val_sutochn := val - FieldByName('Val').AsFloat;  // берется только первое ?

      if(i<>12) then
      begin
      sum_sa_teplo:=sum_sa_teplo+val_sutochn;
      end;

      if(i=12) then
      tepl_sa_obsh:= val_sutochn;
      Close;

        //  по каждому теплосчетчику за вчера
      SQL.Clear;
      SQL.Add('SELECT  * From FloatTable where dateandtime > DATEADD(day,-1,'' '+lblDate.Caption+' 00:00:00'')  and TagIndex='+IntToStr(i)+' order by dateandtime'); //значение
      Open;
      data := FieldByName('DateAndTime').AsString;
      val_yesterday := val - FieldByName('Val').AsFloat-val_sutochn;  // берется только первое ?

      if(i<>12) then
      begin
      sum_sa_teplo_yesterday:=sum_sa_teplo_yesterday+val_yesterday;
      end;

      if(i=12) then
      tepl_sa_obsh_yesterday:= val_yesterday;
      Close;


                       // c начала месяца
      date_month_before:=EncodeDate( myYear,myMonth,1);

      SQL.Clear;
      SQL.Add('SELECT  * From FloatTable where dateandtime > '''+FormatDateTime('yyyy-dd-mm',date_month_before)+' 00:00:00''  and TagIndex='+IntToStr(i)+' order by dateandtime'); //значение
      Open;
      data := FieldByName('DateAndTime').AsString;
      val_month := val - FieldByName('Val').AsFloat;

      if(i<>12) then
      begin
      sum_sa_teplo_month:=sum_sa_teplo_month+val_month;
      end;

      if(i=12) then
      tepl_sa_obsh_month:= val_month;

                        // c начала года


      date_month_before:=EncodeDate( myYear,1,1);
      SQL.Clear;
      SQL.Add('SELECT  * From FloatTable where dateandtime > '''+FormatDateTime('yyyy-dd-mm',date_month_before)+' 00:00:00''  and TagIndex='+IntToStr(i)+' order by dateandtime'); //значение
      Open;
      data := FieldByName('DateAndTime').AsString;
      val_year:= val - FieldByName('Val').AsFloat;

      if(i<>12) then
      begin
      sum_sa_teplo_year:=sum_sa_teplo_year+val_year;
      end;

      if(i=12) then
      tepl_sa_obsh_year:= val_year;



     (Screens[0] as TfrmScreen1).StringGrid1.Cells[i+1,2] := FloatToStr(RoundTo(val,-2));        //заполнение
      Close;
    end;
    (Screens[0] as TfrmScreen1).Label25.Caption:=   FloatToStr(RoundTo(sum_sa_teplo_yesterday,-0)) + '    ';  //суммарное с 12 теплосч за вчера
    (Screens[0] as TfrmScreen1).Label26.Caption:=   FloatToStr(RoundTo(tepl_sa_obsh_yesterday,-0)) + '    ';  //с общего теплосч за вчера

    (Screens[0] as TfrmScreen1).Label1.Caption:=   FloatToStr(RoundTo(sum_sa_teplo,-0)) + '    ';  //суммарное с 12 теплосч с начала суток
    (Screens[0] as TfrmScreen1).Label6.Caption:=   FloatToStr(RoundTo(tepl_sa_obsh,-0)) + '    ';  //с общего теплосч с начала суток

    (Screens[0] as TfrmScreen1).Label9.Caption:=   FloatToStr(RoundTo(sum_sa_teplo_month,-0)) + '    ';  //суммарное с 12 теплосч с начала мес
    (Screens[0] as TfrmScreen1).Label10.Caption:=   FloatToStr(RoundTo(tepl_sa_obsh_month,-0)) + '    ';  //с общего теплосч с начала мес

    (Screens[0] as TfrmScreen1).Label8.Caption:=   FloatToStr(RoundTo(sum_sa_teplo_year,-0)) + '    ';  //суммарное с 12 теплосч с начала года
    (Screens[0] as TfrmScreen1).Label7.Caption:=   FloatToStr(RoundTo(tepl_sa_obsh_year,-0)) + '    ';  //с общего теплосч с начала года

    //именование столбцов и строк
   (Screens[0] as TfrmScreen1).StringGrid1.Cells[13,0] := 'Ob';         //столбцы
    (Screens[0] as TfrmScreen1).StringGrid1.Cells[0,0] := 'Теплосчетчики';  //строка
   (Screens[0] as TfrmScreen1).StringGrid1.Cells[0,1] := 'Показания';       //строка
   (Screens[0] as TfrmScreen1).StringGrid1.Cells[0,2] := 'Сутки';            //строка
    (Screens[0] as TfrmScreen1).StringGrid1.ColWidths[0]:= 80;                //столбцы
  end;
end;




procedure TForm1.GradientRect (FromRGB, ToRGB: TColor; Canvas: TCanvas);
var
  RGBFrom : array[0..2] of Byte; { from RGB values }
  RGBDiff : array[0..2] of integer; { difference of from/to RGB values }
  ColorBand : TRect; { color band rectangular coordinates }
  I : Integer; { color band index }
  R : Byte; { a color band's R value }
  G : Byte; { a color band's G value }
  B : Byte; { a color band's B value }
begin
  { extract from RGB values}
  RGBFrom[0] := GetRValue (ColorToRGB (FromRGB));
  RGBFrom[1] := GetGValue (ColorToRGB (FromRGB));
  RGBFrom[2] := GetBValue (ColorToRGB (FromRGB));
  { calculate difference of from and to RGB values}
  RGBDiff[0] := GetRValue (ColorToRGB (ToRGB)) - RGBFrom[0];
  RGBDiff[1] := GetGValue (ColorToRGB (ToRGB)) - RGBFrom[1];
  RGBDiff[2] := GetBValue (ColorToRGB (ToRGB)) - RGBFrom[2];

  { set pen sytle and mode}
  Canvas.Pen.Style := psSolid;
  Canvas.Pen.Mode := pmCopy;

  { set color band's left and right coordinates}
  ColorBand.Left := 0;
  ColorBand.Right:= canvas.ClipRect.Right-Canvas.ClipRect.Left;

  for I := 0 to $ff do
  begin
    { calculate color band's top and bottom coordinates}
    ColorBand.Top := MulDiv (I , canvas.ClipRect.Bottom-Canvas.ClipRect.Top, $100);
    ColorBand.Bottom := MulDiv (I + 1,canvas.ClipRect.Bottom-Canvas.ClipRect.Top, $100);
    { calculate color band color}
    R := RGBFrom[0] + MulDiv (I, RGBDiff[0], $ff);
    G := RGBFrom[1] + MulDiv (I, RGBDiff[1], $ff);
    B := RGBFrom[2] + MulDiv (I, RGBDiff[2], $ff);
    { select brush and paint color band}
    Canvas.Brush.Color := RGB (R, G, B);
    Canvas.FillRect (ColorBand);
  end;
end;


end.
